<?php

App::uses('AppController', 'Controller');

/**
 * CoreUsersGroups Controller
 *
 * @property CoreUsersGroup $CoreUsersGroup
 */
class CoreUsersGroupsController extends AppController {

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->CoreUsersGroup->recursive = 0;
        $this->set('coreUsersGroups', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->CoreUsersGroup->exists($id)) {
            throw new NotFoundException(__('Invalid core users group'));
        }
        $options = array('conditions' => array('CoreUsersGroup.' . $this->CoreUsersGroup->primaryKey => $id));
        $this->set('coreUsersGroup', $this->CoreUsersGroup->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->CoreUsersGroup->create();
            if ($this->CoreUsersGroup->save($this->request->data)) {
                $this->Session->setFlash(__('The core users group has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core users group could not be saved. Please, try again.'));
            }
        }
        $coreUsers = $this->CoreUsersGroup->CoreUser->find('list');
        $coreGroups = $this->CoreUsersGroup->CoreGroup->find('list');
        $this->set(compact('coreUsers', 'coreGroups'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->CoreUsersGroup->exists($id)) {
            throw new NotFoundException(__('Invalid core users group'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->CoreUsersGroup->save($this->request->data)) {
                $this->Session->setFlash(__('The core users group has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core users group could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('CoreUsersGroup.' . $this->CoreUsersGroup->primaryKey => $id));
            $this->request->data = $this->CoreUsersGroup->find('first', $options);
        }
        $coreUsers = $this->CoreUsersGroup->CoreUser->find('list');
        $coreGroups = $this->CoreUsersGroup->CoreGroup->find('list');
        $this->set(compact('coreUsers', 'coreGroups'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->CoreUsersGroup->id = $id;
        if (!$this->CoreUsersGroup->exists()) {
            throw new NotFoundException(__('Invalid core users group'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->CoreUsersGroup->delete()) {
            $this->Session->setFlash(__('Core users group deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Core users group was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

    public function getGroupsIdFromUser($userId) {
        if(empty($userId)) return array();
        $options = array('conditions' => array('CoreUsersGroup.core_users_id' => $userId));
        $data = $this->CoreUsersGroup->find('all', $options);
        $groups = array();
        foreach ($data as $value) {
            $groups[] = intval($value["CoreUsersGroup"]["core_groups_id"]);
        }
        return $groups;
    }
    
    public function getModulesGroupsPermitionsFromUser($userId) {
        $options = array('conditions' => array('CoreUsersGroup.core_users_id' => $userId));
        $this->CoreUsersGroup->setBypass(true);
        $data = $this->CoreUsersGroup->find('all', $options);
        //var_dump($data);exit;
        $this->CoreUsersGroup->setBypass(false);
        $modules = array();
        App::import('Controller', 'CoreGroups');
        foreach ($data as $value) {
            // get permitions
            $modules = $this->mergePermitions($this->getModulesPermitionsFromGroup($value["CoreUsersGroup"]["core_groups_id"]), $modules);
        }
        return $modules;
    }
    
    public function getModulesPermitionsFromGroup($groupId) {
        App::import('Controller', 'CorePrivilegesGroupsModules');
        $corePrivilegesGroupsModulesController = new CorePrivilegesGroupsModulesController();
        $options = array('conditions' => array('CorePrivilegesGroupsModule.core_groups_id' => $groupId));
        $corePrivilegesGroupsModulesController->CorePrivilegesGroupsModule->setBypass(true);
        $privileges = $corePrivilegesGroupsModulesController->CorePrivilegesGroupsModule->find('all', $options);
        $corePrivilegesGroupsModulesController->CorePrivilegesGroupsModule->setBypass(false);
        foreach ($privileges as $key => $value) {
            if(!empty($value["CorePrivilegesGroupsModule"]["copg_read"])){
                $val = 'read';
            }else if(!empty($value["CorePrivilegesGroupsModule"]["copg_write"])){
                $val = 'write';
            }else if(!empty($value["CorePrivilegesGroupsModule"]["copg_admin"])){
                $val = 'admin';
            }else{
                $val = '';
            }
            $privileges['modulesPrivileges'][$value["CorePrivilegesGroupsModule"]["core_modules_id"]] = $val;
        }
        return $privileges;
    }
    
    public function mergePermitions($permitions1, $permitions2){
        $newPermition = array();
        foreach ($permitions1 as $key => $value) {
            if(empty($permitions2[$key])){
                $newPermition[$key] = $value;
            }else{
                if($this->comparePermitions($permitions1[$key], $permitions2[$key])==1){
                    $newPermition[$key] = $permitions1[$key];
                }else{
                    $newPermition[$key] = $permitions2[$key];
                }
            }
        }
        return $newPermition;
    }
    
    /**
     * Compare 2 permitions 
     * return 1 if permition1 is greater then permition2
     * return -1 if permition1 is lower then permition2
     * return 0 otherwise
     * @param type $permition1
     * @param type $permition2
     * @return int
     */
    private function comparePermitions($permition1, $permition2){
        if($permition1==$permition2){
            return 0;
        }else if($permition1=='admin'){
            return 1;
        }else if($permition2=='admin'){
            return -1;
        }else if($permition1=='write' && $permition2!='write'){
            return 1;
        }else if($permition2=='write'){
            return -1;
        }else if($permition1=='read' && $permition2!='read'){
            return 1;
        }else if($permition2=='read'){
            return -1;
        }
        return 0;
    }

}
